package com.yan.jdbcdemo;

import com.yan.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * @author taoge
 * @Date 2024/8/23 11:08
 * @Description 事务批处理数据
 */
public class JDBCDemo2 {
    // 批处理
    public static void main(String[] args) {
        // 创建连接对象
        Connection connection = null;
        // 创建预编译提交对象
        PreparedStatement ps = null;
        try {
            connection = JDBCUtil.connection();
            // 关闭自动提交事务
            connection.setAutoCommit(false);
            List<Integer> list = Arrays.asList(2, 3, 8);

            String sql = "delete from user where id = ?";

            ps = connection.prepareStatement(sql);
            for (Integer id : list) {
                ps.setObject(1, id);
                // 提交到批处理容器
                ps.addBatch();
            }
            // 一次性提交容器中的sql语句
            int[] result = ps.executeBatch();
            int count = 0;
            for (int i : result) {
                if (i == 1) {
                    count++;
                } else {
                    throw new SQLException("数据错误");
                }
            }
            System.out.println("批处理成功,执行了" + count + "条记录");
            // 提交事务
            connection.commit();

        } catch (SQLException throwables) {
            try {
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            throwables.printStackTrace();
        } finally {
            JDBCUtil.Close(ps, connection);
        }
    }
}
